var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('./common').logger;
var log4js = require('log4js');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var session = require('express-session');
var passport = require('./routes/passport');
var cache = require("./common").RefreshCache;

var app = express();

// set up environment
process.env.PORT = 80;
!process.env.NODE_ENV && (process.env.NODE_ENV = 'development');

// init cache
cache();

// view engine setup
app.set('views', path.join(__dirname, 'app/views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/app/favicon.ico'));
app.use(log4js.connectLogger(logger, {level: 'debug', format: ':method :url'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({
    secret: 'i_fly_dps',
    resave: false,
    saveUninitialized: true
}));
app.use(express.static(path.join(__dirname, 'app')));

passport(app);
routes(app);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    logger.error('Not Found URL : '+req.url);
    err.status = 404;
    next(err);
});

app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('errorTpl', {
        code: err.status ? err.status : 500,
        description: err.message
    });
    console.log(err);
});

module.exports = app;
